<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('商品信息')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :placeholder="$t('请输入商品编码/名称/条码')" v-model="queryParam.goodsInfo"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('上架状态')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select v-model="queryParam.state" @change="handleChange">
                  <a-select-option value="">{{ $t('全部') }}</a-select-option>
                  <a-select-option value="Y">{{ $t('是') }}</a-select-option>
                  <a-select-option value="N">{{ $t('否') }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="handleReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}<a-icon :type="toggleSearchStatus ? 'up' : 'down'"
              /></a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button @click="handleAdd" v-has="'BisGoodsInforController:add'" type="primary" icon="plus">{{
        $t('新增')
      }}</a-button>
    </div>
    <a-row>
      <a-col>
        <a-table
          ref="table"
          size="middle"
          :scroll="{ x: true }"
          bordered
          rowKey="id"
          class="j-table-force-nowrap"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          @change="handleTableChange"
        >
          <template slot="imgSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
            <img v-for="(item,i) in text.split(',')" :key="i"
              v-else
              :src="getImgView(text)"
              height="25px"
              alt=""
              style="max-width: 80px; font-size: 12px; font-style: italic;margin-right:5px"
            />
          </template>
          <span slot="action" slot-scope="text, record">
            <a-popconfirm
              v-has="'BisGoodsInforController:edit'"
              v-if="record.state == 'Y'"
              :title="$t('确定下架吗?')"
              @confirm="() => changeStatus(record.id, record.state)"
            >
              <a>{{ $t('下架') }}</a>
            </a-popconfirm>
            <a-popconfirm
              v-has="'BisGoodsInforController:edit'"
              v-if="record.state == 'N'"
              :title="$t('确定上架吗?')"
              @confirm="() => changeStatus(record.id, record.state)"
            >
              <a>{{ $t('上架') }}</a> </a-popconfirm
            >&nbsp;&nbsp;
            <span v-has="'BisGoodsInforController:edit'">
              <a @click="handleEdit(record)">{{ $t('编辑') }}</a>
            </span>
            &nbsp;&nbsp;
            <a-popconfirm
              v-has="'BisGoodsInforController:delete'"
              :title="$t('确定删除吗?')"
              @confirm="() => handleDelete(record.id)"
            >
              <a>{{ $t('删除') }}</a>
            </a-popconfirm>
            &nbsp;&nbsp;
            <span>
              <a @click="handleEdit(record, true)">{{ $t('详情') }}</a>
            </span>
          </span>
          <template v-for="col in ['sort']" :slot="col" slot-scope="text, record">
            <div :key="col" style="display: flex; justify-content: center">
              <div>
                <a-input
                  v-if="record.editable"
                  style="margin: -5px 0; padding: 0; width: 50px"
                  :value="text"
                  @change="(e) => handleChange(e.target.value, record.id, col)"
                  :maxLength="3"
                />
                <template v-else>{{ text }}</template>
              </div>
              <div v-has="'BisGoodsInforController:edit'" class="editable-row-operations">
                <span v-if="record.editable">
                  <a @click="() => save(record.id)"><a-icon type="save" /></a>
                </span>
                <span v-else>
                  <a :disabled="editingKey !== ''" @click="() => edit(record.id)"><a-icon type="edit" /></a>
                </span>
              </div>
            </div>
          </template>
        </a-table>
      </a-col>
    </a-row>
    <time-limit-coin-modal ref="modalForm" @ok="modalFormOk" />
  </a-card>
</template>

<script>
import Vue from 'vue'
import '@/assets/less/TableExpand.less'
import { getAction, putAction, getFileAccessHttpUrl, deleteAction } from '@/api/manage'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import TimeLimitCoinModal from '../goods/modules/TimeLimitCoinModal'

export default {
  name: 'MemberAddCoin',
  components: {
    TimeLimitCoinModal,
  },
  data() {
    return {
      info: {
        disable: true,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      description: '充币套餐设置管理页面',
      editingKey: '',
      queryParam: {
        column: 'sort',
        order: 'asc',
        goodsInfo: '',
        state: '',
        notSystem: 1,
        form: 15,
      },
      sales: '',
      // 表头
      columns: [
        {
          title: this.$t('排序序号'),
          dataIndex: 'sort',
          align: 'center',
          scopedSlots: { customRender: 'sort' },
          customCell: () => {
            return {
              style: {
                width: '80px',
              },
            }
          },
        },
        {
          title: this.$t('商品形态'),
          align: 'center',
          dataIndex: 'form_dictText',
        },
        {
          title: this.$t('商品编码'),
          align: 'center',
          dataIndex: 'code',
        },
        {
          title: this.$t('商品名称'),
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: this.$t('商品分类'),
          align: 'center',
          dataIndex: 'kindName',
        },
        {
          title: this.$t('上架状态'),
          align: 'center',
          dataIndex: 'state',
          customRender: (text) => (text ? filterMultiDictText(this.dictOptions['state'], text) : ''),
        },
        {
          title: this.$t('参考成本'),
          align: 'right',
          dataIndex: 'cost',
        },
        {
          title: this.$t('是否允许销售'),
          align: 'center',
          dataIndex: 'allowSale',
          customRender: (text) => (text ? filterMultiDictText(this.dictOptions['allowSale'], text) : ''),
        },
        {
          title: this.$t('售价'),
          align: 'right',
          dataIndex: 'price',
        },
        {
          title: this.$t('商品图片'),
          align: 'center',
          dataIndex: 'picture',
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: this.$t('操作'),
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      dataSource: [],
      loading: false,
      url: {
        list: '/goods/bisGoodsInfor/list',
        delete: '/goods/bisGoodsInfor/delete',
        exportXlsUrl: '/goods/bisGoodsInfor/exportXls',
        importExcelUrl: 'sys/common/upload',
      },
      dictOptions: {},
      list: [],
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total', { total: total })
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onShowSizeChange: (current, pageSize) => this.handleSizeChange(current, pageSize),
      },
      toggleSearchStatus: true,
    }
  },
  created() {
    this.$set(this.dictOptions, 'allowOut', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'state', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowWarn', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowSale', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowIntegral', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowCoin', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowLottery', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowAlottery', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowPoints', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowMemberDiscount', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.searchQuery()
  },
  watch: {},
  computed: {
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    handleSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    getGoodsList(num) {
      let that = this
      let querydata = {}
      that.ipagination.current = num
      that.queryParam.pageNo = that.ipagination.current
      that.queryParam.pageSize = that.ipagination.pageSize
      querydata = that.queryParam
      this.loading = true
      getAction('/goods/bisGoodsInfor/list', querydata)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.dataSource.forEach((col) => {
              if (col.validityType == '0') {
                col.validityType_text = this.$t('不限期')
              } else if (col.validityType == '1') {
                col.validityType_text = col.startDate + '~' + col.endDate
              } else {
                col.validityType_text =
                  this.$t('领取后') + col.startDays + this.$t('天生效，有效期') + col.validDays + this.$t('天')
              }
              col.cost = col.cost.toFixed(2)
              col.price = col.price.toFixed(2)
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    modalFormOk() {
      this.getGoodsList(1)
    },
    searchQuery() {
      this.getGoodsList(1)
      this.editingKey = ''
    },
    edit(id) {
      let that = this
      const newData = [...that.dataSource]
      const target = newData.filter((item) => id === item.id)[0]
      this.editingKey = id
      if (target) {
        target.editable = true
        this.dataSource = newData
      }
    },
    save(id) {
      let that = this
      const newData = [...that.dataSource]
      const target = newData.filter((item) => id === item.id)[0]
      if (target) {
        delete target.editable
        let goods = {
          id: target.id,
          sort: target.sort,
        }
        putAction('/goods/bisGoodsInfor/editSort', goods).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.getGoodsList(1)
          } else {
            that.$message.warning(res.message)
          }
        })
      }
      that.editingKey = ''
    },
    handleChangeSales() {
      delete this.queryParam.allowAlottery
      delete this.queryParam.allowCoin
      delete this.queryParam.allowIntegral
      delete this.queryParam.allowLottery
      delete this.queryParam.allowMemberDiscount
      delete this.queryParam.allowOut
      delete this.queryParam.allowPoints
      delete this.queryParam.allowSale
      delete this.queryParam.allowWarn
      switch (this.sales) {
        case 'allowAlottery':
          this.queryParam.allowAlottery = 'Y'
          break
        case 'allowCoin':
          this.queryParam.allowCoin = 'Y'
          break
        case 'allowIntegral':
          this.queryParam.allowIntegral = 'Y'
          break
        case 'allowLottery':
          this.queryParam.allowLottery = 'Y'
          break
        case 'allowMemberDiscount':
          this.queryParam.allowMemberDiscount = 'Y'
          break
        case 'allowOut':
          this.queryParam.allowOut = 'Y'
          break
        case 'allowPoints':
          this.queryParam.allowPoints = 'Y'
          break
        case 'allowSale':
          this.queryParam.allowSale = 'Y'
          break
        case 'allowWarn':
          this.queryParam.allowWarn = 'Y'
          break
      }
    },
    handleChange(value, id, column) {
      const newData = [...this.dataSource]
      const target = newData.filter((item) => id === item.id)[0]
      if (target) {
        target[column] = value
        this.dataSource = newData
      }
    },
    changeStatus(id, state) {
      if (state == 'Y') {
        state = 'N'
      } else if (state == 'N') {
        state = 'Y'
      }
      putAction('/goods/bisGoodsInfor/edit', { id: id, state: state }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getGoodsList(1)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleAdd() {
      this.$refs.modalForm.add('15')
    },
    handleEdit(record, state) {
      this.$refs.modalForm.edit(record, state)
      this.$refs.modalForm.title = this.$t('编辑')
      this.$refs.modalForm.disableSubmit = false
    },
    handleDelete(id) {
      let that = this
      if (!that.url.delete) {
        that.$message.error(that.$t('请设置url.delete属性'))
        return
      }
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message)
          that.getGoodsList(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      this.getGoodsList(pagination.current)
    },
    handleReset() {
      this.queryParam = {
        column: 'sort',
        order: 'asc',
        goodsInfo: '',
        state: '',
        notSystem: 1,
        form: 15,
      }
      this.sales = ''
      this.getGoodsList(1)
    },
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    reCalculatePage(count) {
      //总数量-count
      let total = this.ipagination.total - count
      //获取删除后的分页数
      let currentIndex = Math.ceil(total / this.ipagination.pageSize)
      //删除后的分页数<所在当前页
      if (currentIndex < this.ipagination.current) {
        this.ipagination.current = currentIndex
      }
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>